import { defineStore } from 'pinia'

export const useMessageStore = defineStore('message', {
  state: () => ({
    chatList: [],
    currentChat: null,
    messages: [],
    unreadCount: 0,
    notifications: []
  }),
  
  getters: {
    getChatList: (state) => state.chatList,
    getCurrentChat: (state) => state.currentChat,
    getMessages: (state) => state.messages,
    getUnreadCount: (state) => state.unreadCount,
    getNotifications: (state) => state.notifications
  },
  
  actions: {
    async fetchChatList() {
      try {
        const res = await uni.request({
          url: '/api/chat/list',
          method: 'GET'
        })
        
        if (res.data.code === 0) {
          this.chatList = res.data.data
          return true
        }
        return false
      } catch (error) {
        console.error('Fetch chat list failed:', error)
        return false
      }
    },
    
    async fetchMessages(chatId) {
      try {
        const res = await uni.request({
          url: `/api/chat/${chatId}/messages`,
          method: 'GET'
        })
        
        if (res.data.code === 0) {
          this.messages = res.data.data
          return true
        }
        return false
      } catch (error) {
        console.error('Fetch messages failed:', error)
        return false
      }
    },
    
    async sendMessage(chatId, content) {
      try {
        const res = await uni.request({
          url: `/api/chat/${chatId}/send`,
          method: 'POST',
          data: {
            content
          }
        })
        
        if (res.data.code === 0) {
          this.messages.push(res.data.data)
          return true
        }
        return false
      } catch (error) {
        console.error('Send message failed:', error)
        return false
      }
    },
    
    async createChat(userId) {
      try {
        const res = await uni.request({
          url: '/api/chat/create',
          method: 'POST',
          data: {
            userId
          }
        })
        
        if (res.data.code === 0) {
          this.chatList.unshift(res.data.data)
          return res.data.data.id
        }
        return false
      } catch (error) {
        console.error('Create chat failed:', error)
        return false
      }
    },
    
    async fetchNotifications() {
      try {
        const res = await uni.request({
          url: '/api/notifications',
          method: 'GET'
        })
        
        if (res.data.code === 0) {
          this.notifications = res.data.data
          return true
        }
        return false
      } catch (error) {
        console.error('Fetch notifications failed:', error)
        return false
      }
    },
    
    async readNotification(id) {
      try {
        const res = await uni.request({
          url: `/api/notifications/${id}/read`,
          method: 'POST'
        })
        
        if (res.data.code === 0) {
          const index = this.notifications.findIndex(item => item.id === id)
          if (index !== -1) {
            this.notifications[index].isRead = true
          }
          return true
        }
        return false
      } catch (error) {
        console.error('Read notification failed:', error)
        return false
      }
    },
    
    setCurrentChat(chat) {
      this.currentChat = chat
    },
    
    updateUnreadCount(count) {
      this.unreadCount = count
    },
    
    addMessage(message) {
      this.messages.push(message)
    },
    
    updateChatList(chat) {
      const index = this.chatList.findIndex(item => item.id === chat.id)
      if (index !== -1) {
        this.chatList[index] = chat
      } else {
        this.chatList.unshift(chat)
      }
    }
  }
}) 